package org.oschina.helper.query;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.oschina.helper.query.annotation.Cache;
import org.oschina.helper.query.annotation.Table;
import org.oschina.util.AESUtil;
import org.oschina.util.ReflectUtil;

public class BaseQuery {

	protected int _getCacheTimeout(Class type)
	{
		return _getCacheAnnotation(type).timeout();
	}
	
	protected String _getCacheName(Class type)
	{
		return _getCacheAnnotation(type).name();
	}
	
	protected String _getTableName(Class type)
	{
		return _getTableAnnotation(type).name();
	}
	
	protected Cache _getCacheAnnotation(Class type)
	{
		Cache cache=(Cache) ReflectUtil.getAnnotationByClass(type, Cache.class);
		
		if(cache==null)
			throw new RuntimeException(type.getName()+" 不存在  Cache 注解,无法获得信息");
		
		return cache;
	}
	
	protected Table _getTableAnnotation(Class type)
	{
		Table table=(Table) ReflectUtil.getAnnotationByClass(type, Table.class);
		
		if(table==null)
			throw new RuntimeException(type.getName()+" 不存在  Table 注解,无法获得信息");
		
		return table;
	}
	
	protected String getKey(String key,Object...args)
	{
		StringBuilder stringBuilder=new StringBuilder(key);
		if(args!=null && args.length>0)
		{
			for(Object arg:args)
			{
				stringBuilder.append("_");
				stringBuilder.append(arg);
			}
		}
		return stringBuilder.toString();
	}
	
	/**
	 * 是否超过了最大缓存数量
	 * @param first
	 * @param max
	 * @param maxCount
	 * @return
	 */
	protected boolean maxCacheCount(int first,int max,int maxCount)
	{
		return ((first+max)>maxCount);
	}
	
	/**
	 * 返回ID
	 * @param obj
	 * @return
	 */
	protected Object getId(Object instance)
	{
		if(instance==null)
			return -1;
		
		try
		{
			return BeanUtils.getProperty(instance,"id");
		}
		catch(Exception e)
		{
			return -1;
		}
	}

	/**
	 * 返回数据总数sql
	 * @param tableName
	 * @param where
	 * @return
	 */
	protected String getSumSql(String tableName,String where[])
	{
		return StringUtils.join(new String[]{"SELECT COUNT(*) FROM ",tableName,getWhereSql(where)});
	}
	
	/**
	 * 返回查询语句
	 * @param tableName
	 * @param columns
	 * @param where
	 * @param sort
	 * @param args
	 * @param type
	 * @param first
	 * @param max
	 * @return
	 */
	protected String getSelectSql(String tableName, String[] columns,String[] where,String sort[], Object[] args, Class type, int first, int max)
	{
		StringBuilder sql=new StringBuilder("SELECT ");
		sql.append(getSelectColumns(columns));
		sql.append(" FROM ");
		sql.append(tableName);
		sql.append(getWhereSql(where));
		sql.append(getSort(sort));
		if(first>=0 && max>0)
		{
			sql.append(" LIMIT ");
			sql.append(first);
			sql.append(",");
			sql.append(max);
		}
		return sql.toString();
	}

	/**
	 * 返回key
	 * @param sql
	 * @param args
	 * @return
	 */
	protected String sqlParser(String sql,Object args[])
	{
		String key=getKey(sql, args);
		return AESUtil.encrypt(key).toUpperCase();
	}
	
	/**
	 * 返回查询的字段
	 * @param columns
	 * @return
	 */
	protected String getSelectColumns(String columns[])
	{
		return jointStr("","",columns,",");
	}
	
	/**
	 * 返回条件语句
	 * @param where
	 * @return
	 */
	protected String getWhereSql(String where[])
	{
		return jointStr(" WHERE ","",where," AND ");
	}
	
	/**
	 * 返回排序条件
	 * @param sort
	 * @return
	 */
	protected String getSort(String sort[])
	{
		return jointStr(" ","",sort," ");
	}
	
	/**
	 * 返回更新的字段
	 * @param columns
	 * @return
	 */
	protected String getUpdateColumnSql(String columns[])
	{
		return jointStr(" SET ","",columns,",");
	}
	
	/**
	 * 返回插入的列
	 * @param columns
	 * @param values
	 * @return
	 */
	protected String getInsertColumnSql(String columns[])
	{
		StringBuilder sql=new StringBuilder();
		sql.append(jointStr("(",")",columns,","));
		sql.append(" VALUES");
		String values[]=new String[columns.length];
		for(int i=0;i<columns.length;i++)
			values[i]="?";
		sql.append(jointStr("(",")",values,","));
		return sql.toString();
	}
	
	/**
	 * 获得插入的sql
	 * @param table
	 * @param columns
	 * @return
	 */
	protected String getInsertSql(String table,String columns[])
	{
		return StringUtils.join(new String[]{"INSERT INTO ",table,getInsertColumnSql(columns)});
	}
	
	/**
	 * 获得更新的sql
	 * @param table
	 * @param columns
	 * @param where
	 * @return
	 */
	protected String getUpdateSql(String table,String columns[],String where[])
	{
		return StringUtils.join(new String[]{"UPDATE ",table,getUpdateColumnSql(columns),getWhereSql(where)});
	}
	
	/**
	 * 获得删除的sql
	 * @param table
	 * @param where
	 * @return
	 */
	protected String getDeleteSql(String table,String where[])
	{
		return StringUtils.join(new String[]{"DELETE FROM ",table,getWhereSql(where)});
	}
	
	/**
	 * 拼接字符串
	 * @param start
	 * @param strs
	 * @param joinChar
	 * @return
	 */
	protected String jointStr(String start,String end,String strs[],String joinChar)
	{
		if(strs!=null && strs.length>0)
		{
			StringBuilder str=new StringBuilder(start);
			for(int i=0;i<strs.length;i++)
			{
				str.append(strs[i]);
				if(i!=strs.length-1)
					str.append(joinChar);
			}
			str.append(end);
			return str.toString();
		}
		else
			return "";
	}
}
